package me.flyray.crm.core.biz.personal;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.flyray.common.enums.InOutFlag;
import me.flyray.common.enums.PointsTradeType;
import me.flyray.common.msg.BizResponseCode;
import me.flyray.common.msg.TableResultResponse;
import me.flyray.common.util.DateUtils;
import me.flyray.common.vo.QueryPersonalAccountRequest;
import me.flyray.common.vo.QueryPersonalAccountResponse;
import me.flyray.common.vo.QueryPersonalPointRequest;
import me.flyray.crm.core.entity.*;
import me.flyray.crm.core.mapper.PersonalAccountJournalMapper;
import me.flyray.crm.core.mapper.PersonalAccountMapper;
import me.flyray.crm.core.mapper.PersonalBaseMapper;
import me.flyray.crm.core.mapper.PlatformCoinCustomerMapper;
import me.flyray.crm.core.util.BeanCopyUtils;
import me.flyray.crm.core.util.PageResult;
import me.flyray.crm.facade.request.PersonalAccountRequest;
import me.flyray.crm.facade.response.PersonalPointJournalResponse;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import me.flyray.common.biz.BaseBiz;
import me.flyray.common.util.EntityUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 个人账户信息
 *
 * @author centerroot
 * @email ${email}
 * @date 2018-07-16 10:15:49
 */
@Slf4j
@Service
public class PersonalAccountBiz extends BaseBiz<PersonalAccountMapper, PersonalAccount> {

    @Autowired
    private PersonalAccountMapper personalAccountMapper;
    @Autowired
    private PersonalBaseMapper personalBaseMapper;
    @Autowired
    private PlatformCoinCustomerMapper platformCoinCustomerMapper;
    @Autowired
    private PersonalAccountJournalMapper personalAccountJournalMapper;


    @Value("${toplevel.platform.id}")
    private String toplevelPlatformId;

    /**
     * 查询个人账户信息列表
     *
     * @param queryPersonalBaseListRequest
     * @return
     * @author centerroot
     * @time 创建时间:2018年7月16日下午6:02:38
     */
    public Map<String, Object> queryList(PersonalAccountRequest personalAccountRequest) {
        log.info("【查询个人账户信息列表】   请求参数：{}", EntityUtils.beanToMap(personalAccountRequest));
        Map<String, Object> respMap = new HashMap<String, Object>();
        String platformId = personalAccountRequest.getPlatformId();
        String personalId = personalAccountRequest.getPersonalId();
        int page = personalAccountRequest.getPage();
        int limit = personalAccountRequest.getLimit();

        PersonalAccount personalAccountReq = new PersonalAccount();
        personalAccountReq.setPersonalId(personalId);
        personalAccountReq.setPlatformId(platformId);
        List<PersonalAccount> list = mapper.select(personalAccountReq);
        respMap.put("personalAccountList", list);
        respMap.put("code", BizResponseCode.OK.getCode());
        respMap.put("message", BizResponseCode.OK.getMessage());
        log.info("【查询个人账户信息列表】   响应参数：{}", respMap);
        return respMap;
    }


    /**
     * 微信小程序原力值账户前三排名用户信息查询
     *
     * @param request
     * @return
     */
    public List<Map<String, Object>> forceTopAccountInfo(Map<String, Object> request) {
        log.info("微信小程序原力值账户前三排名用户信息查询.......{}", request);
        PersonalAccount personalAccount = new PersonalAccount();
        personalAccount.setPlatformId((String) request.get("platformId"));
        List<PersonalAccount> selectTopThreeList = personalAccountMapper.selectTopList(personalAccount);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        int num = 1;
        for (PersonalAccount forAccount : selectTopThreeList) {
            Map<String, Object> map = new HashMap<String, Object>();
            String personalId = forAccount.getPersonalId();
            BigDecimal accountBalance = forAccount.getAccountBalance();
            String forceBalance = String.valueOf(accountBalance);
            PersonalBase personalBase = new PersonalBase();
            personalBase.setPlatformId((String) request.get("platformId"));
            personalBase.setPersonalId(personalId);
            PersonalBase selectPersonalBase = personalBaseMapper.selectOne(personalBase);
            String nickname = selectPersonalBase.getNickname();
            String avatar = selectPersonalBase.getAvatar();
            String fireSource = "0.00";
            if (!StringUtils.isEmpty(selectPersonalBase.getIdCard())) {
                PlatformCoinCustomer platformCoinCustomer = new PlatformCoinCustomer();
                platformCoinCustomer.setPlatformId(toplevelPlatformId);//顶级平台编号
                platformCoinCustomer.setIdCard(selectPersonalBase.getIdCard());
                PlatformCoinCustomer selectCoinCustomer = platformCoinCustomerMapper.selectOne(platformCoinCustomer);
                if (null != selectCoinCustomer) {
                    BigDecimal balance = selectCoinCustomer.getBalance();
                    fireSource = String.valueOf(balance);
                }
            }
            map.put("forceBalance", forceBalance);
            map.put("nickname", nickname);
            map.put("avatar", avatar);
            map.put("fireSource", fireSource);
            map.put("num", num);
            list.add(map);
            num++;
        }
        log.info("微信小程序原力值账户前三排名用户信息查询.......{}", list);
        return list;
    }

    /**
     * @param request
     * @return
     */
    public QueryPersonalAccountResponse queryPersonalAcount(QueryPersonalAccountRequest request) {
        PersonalPointAccount personalPointAccount = personalAccountMapper.selectPointAccount(request);
        if (personalPointAccount == null) {
            return null;
        }
        QueryPersonalAccountResponse queryPersonalAccountResponse = new QueryPersonalAccountResponse();
        BeanCopyUtils.copy(personalPointAccount, PersonalPointAccount.class, queryPersonalAccountResponse, QueryPersonalAccountResponse.class);

        queryPersonalAccountResponse.setPoint(String.valueOf(personalPointAccount.getPoint()));
        queryPersonalAccountResponse.setHisPoint(String.valueOf(personalPointAccount.getHisPoint()));
        BigDecimal total = new BigDecimal(0);
        if (null != personalPointAccount.getPoint()) {
            total = total.add(personalPointAccount.getPoint());
        }
        if (null != personalPointAccount.getHisPoint()) {
            total = total.add(personalPointAccount.getHisPoint());
        }
        queryPersonalAccountResponse.setTotalPoint(String.valueOf(total));
        personalPointAccount.setPlatformId(personalPointAccount.getPlatformId());
        return queryPersonalAccountResponse;
    }

    /**
     * @param queryPersonalPointRequest
     * @return
     */
    public TableResultResponse<PersonalPointJournalResponse> queryPointList(QueryPersonalPointRequest queryPersonalPointRequest) {

        Integer currentPage = queryPersonalPointRequest.getCurrentPage();
        Integer pageSize = queryPersonalPointRequest.getPageSize();
        if (pageSize == null || pageSize.intValue() == 0) {
            pageSize = 10;
        }
        if (currentPage == null || currentPage.intValue() == 0) {
            currentPage = 1;
        }
        Integer startRow = (currentPage - 1) * pageSize;
        int count = personalAccountJournalMapper.countPersonalPointJournal(queryPersonalPointRequest);
        List<PersonalPointJournal> personalPointJournals = null;
        List<PersonalPointJournalResponse> list = new ArrayList<>();
        if (count > 0) {
            personalPointJournals = personalAccountJournalMapper.queryPersonalPointJournal(queryPersonalPointRequest, startRow, pageSize);
            personalPointJournals.stream().forEach(personalPointJournal -> {
                PersonalPointJournalResponse personalPointJournalResponse = new PersonalPointJournalResponse();
                BeanCopyUtils.copy(personalPointJournal, personalPointJournal.getClass(), personalPointJournalResponse, personalPointJournalResponse.getClass());
                if (personalPointJournal.getInOutFlag().equals(InOutFlag.in.getCode())) {
                    //获取明年的时间点
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    String lastYear = sdf.format(personalPointJournal.getCreateTime());
                    personalPointJournalResponse.setValidDate(lastYear + "-12-31");
                }
                //前端约定数字-5
                if(!org.apache.commons.lang.StringUtils.isBlank(personalPointJournalResponse.getTradeType()))
                    personalPointJournalResponse.setTradeType(String.valueOf(Integer.parseInt(personalPointJournalResponse.getTradeType()) - 5));
                list.add(personalPointJournalResponse);
            });
        }
        return new TableResultResponse<>(count, list);
    }

}